package cn.micro.system.manage.annotate.impl;

import cn.micro.system.manage.annotate.UniqueDept;
import cn.micro.system.manage.entity.SysDimDept;
import cn.micro.system.manage.service.SysDimDeptService;
import javax.annotation.Resource;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.annotation.Annotation;
import java.util.function.Predicate;

public class DeptValidation <T extends Annotation> implements ConstraintValidator<T, SysDimDept> {

    protected Predicate<SysDimDept> predicate = c -> true;

    @Resource
    protected SysDimDeptService sysDimDeptService;

    @Override
    public boolean isValid(SysDimDept sysDimDept, ConstraintValidatorContext constraintValidatorContext) {
        return sysDimDeptService == null || predicate.test(sysDimDept);
    }

    /**
     * 校验部门编码或者部门名称是否重复
     */
    public static class UniqueDeptValidate extends DeptValidation<UniqueDept>{
        @Override
        public void initialize(UniqueDept constraintAnnotation) {
            predicate = c -> sysDimDeptService.getByName(c).isEmpty();
        }
    }
}
